package s3

import (
	"fmt"
	"git.supremind.info/product/box/vehicle/common"
	"git.supremind.info/product/box/vehicle/internal/vmr"
	"github.com/minio/minio-go"
	"net/http"
	"strings"
	"sync"
)

type singleton struct {
	enable      bool
	minioClient *minio.Client
	platformS3  vmr.S3
}

var ins *singleton
var mu sync.Mutex

func PlatformInstance() *singleton {
	if ins == nil {
		mu.Lock()
		defer mu.Unlock()
		if ins == nil {
			ins = &singleton{}
		}
	}
	return ins
}

func (c *singleton) Enabled() bool {
	return c.enable
}

func (c *singleton) InitMinioClient(platformS3 vmr.S3) {
	mu.Lock()
	defer mu.Unlock()
	if !strings.Contains(platformS3.Endpoint, "http") {
		platformS3.Endpoint = "http://" + platformS3.Endpoint
	}
	client, _ := minio.New(platformS3.Endpoint, platformS3.Ak, platformS3.Sk, false)
	c.minioClient = client
	c.enable = true
}

func (c *singleton) DisAbleMinioClient() {
	mu.Lock()
	defer mu.Unlock()
	c.enable = false
}

func (c *singleton) PutObject(objectName, url string) (string, error) {
	if !c.enable {
		return "", nil
	}

	client := http.DefaultClient
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		common.Logger.Error(err)
		return "", err
	}

	resp, err := client.Do(req)
	defer resp.Body.Close()

	if err != nil {
		common.Logger.Error(err)
		return "", err
	}

	const bucketName = "default"
	_, err = c.minioClient.PutObject(bucketName, objectName, resp.Body, resp.ContentLength, minio.PutObjectOptions{ContentType: "application/octet-stream"})
	if err != nil {
		common.Logger.Error(err)
		return "", err
	}

	urlPrefix := c.platformS3.Endpoint
	if !strings.HasPrefix(urlPrefix, "http") {
		urlPrefix = "http://" + urlPrefix
	}

	return fmt.Sprintf("%s/%s/%s", urlPrefix, c.platformS3.Bucket, objectName), nil
}
